package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Category;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorsMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class DishServiceImpl implements DishService {
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorsMapper dishFlavorsMapper;

    @Autowired
    private SetmealDishMapper setmealDishMapper;

    /**
     * 批量删除
     *
     * @param ids
     */
    @Override
    @Transactional
    public void delDishes(Long[] ids) {
        // 查询菜品信息，  是否停售  未停售的商品不可删除
        for (Long id : ids) {
            Dish dish = dishMapper.selectById(id);
            if (dish.getStatus().equals(StatusConstant.ENABLE)) {
                // 当前商品处于起售中， 不可删除
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        }
        // 判断当前菜品是否被套餐关联
        List<Long> setemealIds = setmealDishMapper.getSetmealIdsByDishIds(ids);
        if (setemealIds != null && setemealIds.size() > 0) {
            // 当前菜品被套餐关联了  不可删除
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }
        // 删除菜品表的数据
        for (Long id : ids) {
            dishMapper.deleteById(id);
            // 删除口味表中的id
            dishFlavorsMapper.deleteByDishId(id);
        }
    }

    /**
     * 增加菜品 和 口味
     *
     * @param dishDTO
     */
    @Override
    @Transactional // 多表开启事务
    public void addDishWithFlavors(DishDTO dishDTO) {
        //DTO --> entity
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        // 向菜品表添加数据（1条）  dish
        dishMapper.insert(dish);

        // 获取insert生成的ID  --->dishID
        Long dishId = dish.getId();

        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors != null && flavors.size() > 0) {
            flavors.forEach(dishFlavor -> {
                dishFlavor.setDishId(dishId);
            });
            // 向口味表添加数据（N条）  dish_flavors
            dishFlavorsMapper.insertBatch(flavors);
        }
    }

    /**
     * 分页查询
     *
     * @param dishPageQueryDTO
     * @return
     */
    @Override
    public PageResult list(DishPageQueryDTO dishPageQueryDTO) {
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());
        Page<DishVO> page = dishMapper.selectPage(dishPageQueryDTO);
        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 根据Id查询菜品信息和关联的口味信息
     *
     * @param id
     * @return
     */

    @Override
    public DishVO getByIdWithFlavor(Long id) {
        // 根据ID查询菜品数据
        Dish dish = dishMapper.selectById(id);
        // 根据菜品ID查询口味数据
        List<DishFlavor> dishFlavors = dishFlavorsMapper.selectByDishId(id);
        // 将数据封装到VO
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish, dishVO);
        dishVO.setFlavors(dishFlavors);
        return dishVO;
    }

    /**
     * 修改菜品和口味数据
     *
     * @param dishDTO
     */
    @Override
    @Transactional  // 开启事务
    public void updateDishAndFlavor(DishDTO dishDTO) {
        // DTO ----> entity
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        // 更新菜品数据
        dishMapper.update(dish);
        // 先将原先的口味进行删除，再进行插入  形成一个修改的效果
        // 删除
        dishFlavorsMapper.deleteByDishId(dishDTO.getId());

        List<DishFlavor> flavors = dishDTO.getFlavors();
        // 判断是否有口味
        if (flavors != null && flavors.size() > 0) {
            flavors.forEach(dishFlavor -> {
                dishFlavor.setDishId(dishDTO.getId());
            });
            // 向口味表插入数据
            dishFlavorsMapper.insertBatch(flavors);
        }
    }

    /**
     * 修改菜品状态
     *
     * @param status
     * @param id
     */
    @Override
    public void editStatus(Integer status, Long id) {
        // 转化entity
        Dish dish = Dish.builder()
                .id(id)
                .status(status)
                .build();
        // 更新数据
        dishMapper.update(dish);
    }

    /**
     * 根据分类ID查询菜品
     *
     * @param categoryId
     * @return
     */
    @Override
    public List<Dish> listByCategoryId(Long categoryId) {
        Dish dish = Dish.builder()
                .categoryId(categoryId)
                .status(StatusConstant.ENABLE)
                .build();
        // 查询状态未启售的菜品
        List<Dish> dishes = dishMapper.selectByCategoryIdAndStatus(dish);
        return dishes;
    }

    /**
     * 根据分类ID查询菜品
     *
     * @param categoryId
     * @return
     */
    @Override
    public List<DishVO> query(Dish dish) {
        // 通过categoryID查询菜品  list
        List<Dish> dishes = dishMapper.selectByCategoryIdAndStatus(dish);
        List<DishVO> dishVOList = new ArrayList<>();
        // 循环查询
        for (Dish dishItem : dishes) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(dishItem, dishVO);
            // 根据菜品查询口味
            List<DishFlavor> dishFlavors = dishFlavorsMapper.selectByDishId(dishItem.getId());
            dishVO.setFlavors(dishFlavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }

}
